package demo;

import java.io.*;
import java.nio.charset.Charset;
import java.util.Scanner;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class CopyDemo {
    public static void main(String[] args) {
//        /*复制文件*/
//        copyFile("C:\\Users\\0143703\\Desktop\\新建文本文档.txt","C:\\Users\\0143703\\Desktop\\常用数据.txt");
//        /*简易记事本*/
//        note();
//        /*读取指定文件*/
//        readFile("hello.txt");
//        zipFile("C:\\Users\\0143703\\Desktop\\笔记\\摘录.txt","压缩.zip");

        toZip("C:\\Users\\0143703\\Desktop\\笔记", "C:\\Users\\0143703\\Desktop\\笔记副本", true);
    }

    /**
     * 复制文件
     *
     * @param sourcePath 源文件路径
     * @param destPath   目标文件路径
     */
    public static void copyFile(String sourcePath, String destPath) {
        try (RandomAccessFile source = new RandomAccessFile(sourcePath, "r");
             RandomAccessFile dest = new RandomAccessFile(destPath, "rw")) {

            byte[] data = new byte[1024 * 10];
            int len;
            long start = System.currentTimeMillis();
            while ((len = source.read(data)) != -1) {
                dest.write(data, 0, len);
            }
            long end = System.currentTimeMillis();
            System.out.println("共耗时:" + (end - start) + "ms");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*简易记事本*/
    public static void note() {
        System.out.println("请输入文件名:");
        Scanner scan = new Scanner(System.in);
        String fileName = scan.nextLine();
        try (PrintWriter pw = new PrintWriter(
                new BufferedWriter(
                        new OutputStreamWriter(
                                new FileOutputStream("C:\\Users\\0143703\\Desktop\\" + fileName + ".txt", true),
                                "UTF-8"
                        )
                ), true
        )) {
            System.out.println("输入exit时,退出");
            while (true) {
                System.out.println("开始记录:");
                String line = scan.nextLine();
                if ("exit".equals(line)) {
                    break;
                }
                pw.println(line);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取指定文件
     *
     * @param pathname 文件路径
     */
    public static void readFile(String pathname) {
        File file = new File(pathname);
        if (!file.exists()) {
            System.out.println("文件不存在");
            return;
        }
        try (BufferedReader br = new BufferedReader(
                new InputStreamReader(
                        new FileInputStream(file)))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
                Thread.sleep(1000);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 压缩文件到指定位置
     *
     * @param filePath 要压缩文件路径
     * @param zipPath  压缩后文件路径
     */
    public static void zipFile(String filePath, String zipPath) {
        if (filePath == null) {
            return;
        }
        File zipFile = new File(zipPath);
        ZipOutputStream out = null;
        try {
            out = new ZipOutputStream(new FileOutputStream(zipFile), Charset.forName("utf-8"));
            File infile = new File(filePath);
            if (infile.exists()) {
                ZipEntry zipEntry = new ZipEntry(infile.getName());
                out.putNextEntry(zipEntry);
                int len = 0;
                byte[] buffer = new byte[1024 * 10];
                FileInputStream in = new FileInputStream(infile);
                while ((len = in.read(buffer)) != -1) {
                    out.write(buffer, 0, len);
                    out.flush();
                }
                out.closeEntry();
                in.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 压缩成ZIP 方法1
     * @param srcDir 压缩文件夹路径
     * @param destDir    压缩后文件夹路径
     * @param KeepDirStructure  是否保留原来的目录结构,true:保留目录结构;
     *                   false:所有文件跑到压缩包根目录下(注意：不保留目录结构可能会出现同名文件,会压缩失败)
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    public static void toZip(String srcDir, String destDir, boolean KeepDirStructure)
            throws RuntimeException{
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null ;
        try {
            zos = new ZipOutputStream(new FileOutputStream(destDir), Charset.forName("utf-8"));
            File sourceFile = new File(srcDir);
           compress(sourceFile,zos,sourceFile.getName(),KeepDirStructure);
            long end = System.currentTimeMillis();
            System.out.println("压缩完成，耗时：" + (end - start) +" ms");
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils",e);
        }finally{
            if(zos != null){
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    /**
     * 递归压缩方法
     * @param sourceFile 源文件
     * @param zos        zip输出流
     * @param name       压缩后的名称
     * @param KeepDirStructure  是否保留原来的目录结构,true:保留目录结构;
     *                          false:所有文件跑到压缩包根目录下(注意：不保留目录结构可能会出现同名文件,会压缩失败)
     * @throws Exception
     */
    private static void compress(File sourceFile, ZipOutputStream zos, String name,
                                 boolean KeepDirStructure) throws Exception{
        byte[] buf = new byte[10* 1024];
        if(sourceFile.isFile()){
            // 向zip输出流中添加一个zip实体，构造器中name为zip实体的文件的名字
            zos.putNextEntry(new ZipEntry(name));
            // copy文件到zip输出流中
            int len;
            FileInputStream in = new FileInputStream(sourceFile);
            while ((len = in.read(buf)) != -1){
                zos.write(buf, 0, len);
            }
            // Complete the entry
            zos.closeEntry();
            in.close();
        } else {
            File[] listFiles = sourceFile.listFiles();
            if(listFiles == null || listFiles.length == 0){
                // 需要保留原来的文件结构时,需要对空文件夹进行处理
                if(KeepDirStructure){
                    // 空文件夹的处理
                    zos.putNextEntry(new ZipEntry(name + "/"));
                    // 没有文件，不需要文件的copy
                    zos.closeEntry();
                }
            }else {
                for (File file : listFiles) {
                    // 判断是否需要保留原来的文件结构
                    if (KeepDirStructure) {
                        // 注意：file.getName()前面需要带上父文件夹的名字加一斜杠,
                        // 不然最后压缩包中就不能保留原来的文件结构,即：所有文件都跑到压缩包根目录下了
                        compress(file, zos, name + "/" + file.getName(), true);
                    } else {
                        compress(file, zos, file.getName(), false);
                    }
                }
            }
        }
    }
}
